const express = require('express')
const path = require('path')
const models = require(path.join(__dirname,'../db/db'));

const router = express.Router()
const mysql = require('mysql');
const $sql = require(path.join(__dirname,'../db/sqlMap'));

const conn = mysql.createConnection(models.mysql);
conn.connect();

let isLogin = []
let isRegister = []

// 登录接口
router.post('/login',(req,res)=>{
	const user = req.body;
	// const sel_email = $sql.user.select + " where email = '" + user.email + "'";
	const sel_username = $sql.user.select;

	// console.log(sel_username);
	conn.query(sel_username, user.username, (error, results)=>{
		if (error) {
			throw error;
		}
		// console.log(results)
		// if (results[0] === undefined) {
		// 	res.send("-1");  // -1 表示查询不到，用户不存在，即邮箱填写错误
		// } else{
		// 	if (results[0].username == user.username && results[0].password == user.password) {
		// 		res.send("0");  // 0 表示用户存在并且邮箱密码正确
		// 	} else{
		// 		res.send("1");  // 1 表示用户存在，但密码不正确
		// 	}
		// }

    if(results == undefined){
      res.send("-1")
    }else{
      isLogin = [];
      // 匹配输入的用户名密码
      results.forEach((item)=>{
        if(item.username == user.username && item.password == user.password){
          isLogin.push(item)
        }
      })
      if(isLogin.length !== 0 ){
        res.send('0')
      }else{
        res.send('1')
      }
    }
	})
});

// 注册接口
router.post('/add', (req, res) => {
	const params = req.body;
	const sel_sql = $sql.user.select + " where username = '" + params.username + "'";
	const add_sql = $sql.user.add;
	
	conn.query(sel_sql, params.username, (error, results) => {
		if(error) {
			console.log(err);
		}
    isRegister = []
    results.forEach((item)=>{
      if(item.username == params.username){
        isRegister.push(item)
      }
    })

    if(isRegister.length !== 0 && results.length !== 0){
      res.send("-1")
    }else{
      conn.query(add_sql, [params.username, params.password], (err, rst) => {
        if (err) {
          console.log(err);
        } else{
          // console.log(rst);
          res.send("0"); // 0 表示用户创建成功
        }
      });
    }
	});
});

module.exports = router